<template>
  <view class="page-container">
    <view class="page-header">
      <text class="header-title">添加古树信息</text>
    </view>

    <scroll-view class="form-container" scroll-y>
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">位置信息</text>
        </view>

        <view class="form-item">
          <text class="label">获取位置方式</text>
          <view class="location-method">
            <button :class="['method-btn', locationMethod === 'gps' ? 'active' : '']"
              @tap="selectLocationMethod('gps')">
              GPS定位
            </button>
            <button :class="['method-btn', locationMethod === 'manual' ? 'active' : '']"
              @tap="selectLocationMethod('manual')">
              手动选择
            </button>
          </view>
        </view>

        <!-- GPS定位方式 -->
        <view v-if="locationMethod === 'gps'">
          <view class="form-item">
            <button class="location-btn" @tap="getLocation">
              <text class="btn-text" v-if="!treeInfo.gpsLatitude">获取当前位置</text>
              <text class="btn-text" v-else>重新获取位置</text>
            </button>
          </view>

          <view class="form-item" v-if="treeInfo.gpsLatitude && treeInfo.gpsLongitude">
            <text class="label">当前位置</text>
            <view class="location-display">
              <text class="location-text">
                纬度: {{ treeInfo.gpsLatitude }}
              </text>
              <text class="location-text">
                经度: {{ treeInfo.gpsLongitude }}
              </text>
            </view>
          </view>

          <view class="form-item" v-if="treeInfo.provinceName">
            <text class="label">省市区</text>
            <view class="location-display">
              <text class="location-text">
                {{ treeInfo.provinceName }} {{ treeInfo.cityName }} {{ treeInfo.districtName }}
              </text>
            </view>
          </view>
        </view>

        <!-- 手动选择方式 -->
        <view v-if="locationMethod === 'manual'">
          <view class="form-item">
            <text class="label">省</text>
            <picker mode="selector" :range="provinceList" range-key="fullname" @change="onProvinceChange">
              <view class="picker">
                <text class="picker-text">{{ selectedProvince.fullname || "请选择省" }}</text>
                <text class="icon-arrow">▶</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">市</text>
            <picker mode="selector" :range="cityList" range-key="fullname" @change="onCityChange">
              <view class="picker">
                <text class="picker-text">{{ selectedCity.fullname || "请选择市" }}</text>
                <text class="icon-arrow">▶</text>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="label">区/县</text>
            <picker mode="selector" :range="districtList" range-key="fullname" @change="onDistrictChange">
              <view class="picker">
                <text class="picker-text">{{ selectedDistrict.fullname || "请选择区/县" }}</text>
                <text class="icon-arrow">▶</text>
              </view>
            </picker>
          </view>
        </view>

        <view class="form-item">
          <text class="label">详细地址 *</text>
          <input class="input" placeholder="请输入详细地址" v-model="treeInfo.locationAddress" />
        </view>
      </view>

      <view class="form-section">
        <view class="section-title">
          <text class="title-text">基本信息</text>
        </view>

        <view class="form-item">
          <text class="label">中文名称 *</text>
          <input class="input" placeholder="请输入古树中文名称" v-model="treeInfo.chineseName" />
        </view>
        <view class="form-item">
          <text class="label">拉丁学名</text>
          <input class="input" placeholder="请输入拉丁学名" v-model="treeInfo.scientificName" maxlength="100" />
        </view>
        <view class="form-item">
          <text class="label">科名 *</text>
          <input class="input" placeholder="请输入科名" v-model="treeInfo.familyName" />
        </view>

        <view class="form-item">
          <text class="label">属名 *</text>
          <input class="input" placeholder="请输入属名" v-model="treeInfo.genusName" />
        </view>

        <view class="form-item">
          <text class="label">树龄 *</text>
          <input class="input" type="number" placeholder="请输入树龄" v-model="treeInfo.estimatedAge" />
        </view>

        <view class="form-item">
          <text class="label">保护等级 *</text>
          <picker mode="selector" :range="protectionLevels" range-key="label" @change="onProtectionLevelChange">
            <view class="picker">
              <text class="picker-text">{{ protectionLevelText || "请选择保护等级" }}</text>
              <text class="icon-arrow">▶</text>
            </view>
          </picker>
        </view>
      </view>

      <view class="form-section">
        <view class="section-title">
          <text class="title-text">详细描述</text>
        </view>

        <view class="form-item">
          <text class="label">描述</text>
          <textarea class="textarea" placeholder="请输入古树历史或特征描述" v-model="treeInfo.description" />
        </view>
      </view>

      <!-- 图片上传部分 -->
      <view class="form-section">
        <view class="section-title">
          <text class="title-text">古树图片</text>
          <text class="subtitle">(最多5张)</text>
        </view>

        <view class="form-item">
          <view class="image-upload-container">
            <view class="image-list">
              <view v-for="(image, index) in treeInfo.images" :key="index" class="image-item">
                <image :src="image" class="uploaded-image" mode="aspectFill" />
                <button class="delete-image-btn" @tap="deleteImage(index)">
                  <text class="icon-delete">✕</text>
                </button>
              </view>
              <view class="image-upload-btn" @tap="chooseImage" v-if="treeInfo.images.length < 5">
                <text class="icon-add">+</text>
                <text class="upload-text">上传图片</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="form-actions">
        <button class="cancel-btn" @tap="closeAddForm">
          <text class="btn-text">取消</text>
        </button>
        <button class="submit-btn" @tap="submitTreeInfo">
          <text class="btn-text">提交</text>
        </button>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { addTreeAPI } from '@/services/tree'

// 地图相关数据
const latitude = ref(39.909)
const longitude = ref(116.39742)

const covers = ref([{
  latitude: 39.909,
  longitude: 116.39742,
  iconPath: '/static/icon/map-icon/green.png'
}])

const uploadedImages = ref([])
// 添加古树功能
const showAddForm = ref(false)
const locationMethod = ref('gps') // 'gps' 或 'manual'

// 古树信息对象
// 古树信息对象
const treeInfo = ref({
  chineseName: '',
  familyName: '',
  genusName: '',
  scientificName: '', // 添加这一行
  estimatedAge: null,
  protectionLevel: null,
  gpsLongitude: null,
  gpsLatitude: null,
  provinceCode: '',
  provinceName: '',
  cityCode: '',
  cityName: '',
  districtCode: '',
  districtName: '',
  locationAddress: '',
  description: '',
  images: []
})
// 行政区划数据
const provinceList = ref([])
const cityList = ref([])
const districtList = ref([])
const selectedProvince = ref({})
const selectedCity = ref({})
const selectedDistrict = ref({})

// 保护等级选项
const protectionLevels = ref([
  { label: '一级保护', value: 1 },
  { label: '二级保护', value: 2 },
  { label: '三级保护', value: 3 },
  { label: '四级保护', value: 4 },
  { label: '五级保护', value: 5 }
])
const protectionLevelText = ref('')

const isSubmitting = ref(false)
// 关闭添加古树表单
const closeAddForm = () => {
  treeInfo.value = {
    chineseName: '',
    familyName: '',
    genusName: '',
    estimatedAge: null,
    protectionLevel: null,
    gpsLongitude: null,
    gpsLatitude: null,
    provinceCode: '',
    provinceName: '',
    cityCode: '',
    cityName: '',
    districtCode: '',
    districtName: '',
    locationAddress: '',
    description: '',
    images: []
  }
  locationMethod.value = 'gps'
  selectedProvince.value = {}
  selectedCity.value = {}
  selectedDistrict.value = {}
  cityList.value = []
  districtList.value = []
  protectionLevelText.value = ''

  // 返回上一页
  uni.navigateBack()
}

// 选择位置获取方式
const selectLocationMethod = (method) => {
  locationMethod.value = method
}

// 获取当前位置
const getLocation = () => {
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
    console.log('原始定位结果:', res); // 添加这行查看原始数据
      treeInfo.value.gpsLatitude = res.latitude.toFixed(7)
      treeInfo.value.gpsLongitude = res.longitude.toFixed(7)
      getAddressFromLocation(res.latitude, res.longitude)
    },
    fail: (err) => {
      uni.showToast({
        title: '获取位置失败',
        icon: 'none'
      })
      console.error('获取位置失败:', err)
    }
  })
}

// 通过经纬度获取地址信息
const getAddressFromLocation = (latitude, longitude) => {
  uni.request({
    url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=CZDBZ-Z6267-K4EXF-PNOAB-BYUE3-ROB2P&libraries=service&get_poi=1`,
    success: (res) => {
      if (res.data.status === 0) {
        const result = res.data.result
        treeInfo.value.provinceName = result.ad_info.province
        treeInfo.value.cityName = result.ad_info.city
        treeInfo.value.districtName = result.ad_info.district
        treeInfo.value.provinceCode = result.ad_info.adcode.substring(0, 2) + '0000'
        treeInfo.value.cityCode = result.ad_info.adcode.substring(0, 4) + '00'
        treeInfo.value.districtCode = result.ad_info.adcode
        treeInfo.value.locationAddress = result.address
      }
    }
  })
}

// 初始化行政区划数据
const initRegionData = () => {
  uni.request({
    url: 'https://apis.map.qq.com/ws/district/v1/list?key=CZDBZ-Z6267-K4EXF-PNOAB-BYUE3-ROB2P&libraries=service',
    success: (res) => {
      if (res.data.status === 0) {
        provinceList.value = res.data.result[0]
      }
    }
  })
}

// 省份选择变化
const onProvinceChange = (e) => {
  const index = e.detail.value
  selectedProvince.value = provinceList.value[index]

  treeInfo.value.provinceCode = provinceList.value[index].id
  treeInfo.value.provinceName = provinceList.value[index].fullname

  getCityList(provinceList.value[index].id)
}

// 获取市列表
const getCityList = (provinceId) => {
  uni.request({
    url: `https://apis.map.qq.com/ws/district/v1/getchildren?id=${provinceId}&key=CZDBZ-Z6267-K4EXF-PNOAB-BYUE3-ROB2P&libraries=service`,
    success: (res) => {
      if (res.data.status === 0) {
        cityList.value = res.data.result[0] || []
      }
    }
  })

  // 重置区县数据
  districtList.value = []
  selectedCity.value = {}
  selectedDistrict.value = {}
}

// 市选择变化
const onCityChange = (e) => {
  const index = e.detail.value
  selectedCity.value = cityList.value[index]

  treeInfo.value.cityCode = cityList.value[index].id
  treeInfo.value.cityName = cityList.value[index].fullname

  getDistrictList(cityList.value[index].id)
}

// 获取区县列表
const getDistrictList = (cityId) => {
  uni.request({
    url: `https://apis.map.qq.com/ws/district/v1/getchildren?id=${cityId}&key=CZDBZ-Z6267-K4EXF-PNOAB-BYUE3-ROB2P&libraries=service`,
    success: (res) => {
      if (res.data.status === 0) {
        districtList.value = res.data.result[0] || []
      }
    }
  })

  selectedDistrict.value = {}
}

// 区县选择变化
const onDistrictChange = (e) => {
  const index = e.detail.value
  selectedDistrict.value = districtList.value[index]

  treeInfo.value.districtCode = districtList.value[index].id
  treeInfo.value.districtName = districtList.value[index].fullname
}

// 保护等级选择变化
const onProtectionLevelChange = (e) => {
  const index = e.detail.value
  treeInfo.value.protectionLevel = protectionLevels.value[index].value
  protectionLevelText.value = protectionLevels.value[index].label
}

// 提交古树信息
const submitTreeInfo = async () => {
  // 验证必填字段
  if (!treeInfo.value.chineseName) {
    uni.showToast({ title: '请输入中文名称', icon: 'none' })
    return
  }

  if (!treeInfo.value.familyName) {
    uni.showToast({ title: '请输入科名', icon: 'none' })
    return
  }

  if (!treeInfo.value.genusName) {
    uni.showToast({ title: '请输入属名', icon: 'none' })
    return
  }

  if (!treeInfo.value.estimatedAge) {
    uni.showToast({ title: '请输入树龄', icon: 'none' })
    return
  }

  if (!treeInfo.value.protectionLevel) {
    uni.showToast({ title: '请选择保护等级', icon: 'none' })
    return
  }

  if (!treeInfo.value.locationAddress) {
    uni.showToast({ title: '请输入详细地址', icon: 'none' })
    return
  }

  // 根据位置获取方式设置位置信息
  if (locationMethod.value === 'manual') {
    if (!selectedProvince.value.fullname || !selectedCity.value.fullname || !selectedDistrict.value.fullname) {
      uni.showToast({ title: '请选择完整的省市区信息', icon: 'none' })
      return
    }
  } else {
    if (!treeInfo.value.gpsLatitude || !treeInfo.value.gpsLongitude) {
      uni.showToast({ title: '请获取当前位置', icon: 'none' })
      return
    }
  }

  isSubmitting.value = true

  try {
    // 上传图片
    let imageUrls = []
    if (treeInfo.value.images.length > 0) {
      imageUrls = await uploadImages()
    }

    // 构造提交数据
    const submitData = {
      ...treeInfo.value,
      estimatedAge: parseInt(treeInfo.value.estimatedAge),
      images: imageUrls // 使用上传后的图片URL
    }

    // 调用API提交数据
    console.log('提交的古树信息:', submitData)
    const result = await addTreeAPI(submitData)
    if (result.code === 1) {
      uni.showModal({
        title: '提交成功',
        content: '古树信息已提交',
        showCancel: false,
        success: () => {
          closeAddForm()
        }
      })
    }
  } catch (error) {
    console.error('提交出错:', error)
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    })
  } finally {
    isSubmitting.value = false
  }
}

// 选择图片
// 添加上传图片相关状态
const isUploading = ref(false)

// 修改 chooseImage 方法
const chooseImage = () => {
  uni.chooseImage({
    count: 5 - treeInfo.value.images.length, // 最多5张
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      // 直接将临时路径添加到列表中，稍后在提交时上传
      treeInfo.value.images = [...treeInfo.value.images, ...res.tempFilePaths]
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

// 上传图片到服务器
const uploadImages = async () => {
  const imageUrls = []

  // 修改这里：使用 treeInfo.value.images 而不是 uploadedImages.value
  for (let i = 0; i < treeInfo.value.images.length; i++) {
    const tempFilePath = treeInfo.value.images[i]

    // 使用uni.uploadFile上传图片
    const uploadResult = await new Promise((resolve) => {
      uni.uploadFile({
        url: '/uploadFile', // 替换为实际的上传接口地址
        filePath: tempFilePath,
        name: 'file',
        formData: {
          path: 'issueImages',
        },
        /* header: {
          // 如果需要认证token，可以在这里添加
          // 'Authorization': 'Bearer ' + token
        }, */
        success: (uploadRes) => {
          resolve(uploadRes)
        },
        fail: (error) => {
          resolve(null)
        }
      })
    })

    console.log('uploadResult', uploadResult)
    if (uploadResult && uploadResult.statusCode === 200) {
      // 假设返回的数据中包含图片URL
      const result = JSON.parse(uploadResult.data)
      console.log('上传成功result:', result)
      imageUrls.push(result.data) // 根据实际API返回结构调整
      console.log('上传成功imageUrls:', imageUrls)
    }
  }
  return imageUrls
}
// 删除图片
const deleteImage = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        treeInfo.value.images.splice(index, 1);
      }
    }
  });
};

// 页面加载时初始化数据
initRegionData()
</script>

<style lang="scss">
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

.page-header {
  padding: 30rpx;
  background: linear-gradient(90deg, #4CAF50, #2E7D32);
  color: white;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
}

.form-container {
  flex: 1;
  padding: 30rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  position: relative;
  padding-left: 15rpx;
}

.title-text::before {
  content: '';
  position: absolute;
  left: 0;
  top: 5rpx;
  width: 8rpx;
  height: 32rpx;
  background-color: #4CAF50;
  border-radius: 4rpx;
}

.subtitle {
  font-size: 24rpx;
  color: #999;
  margin-left: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  margin-bottom: 15rpx;
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.input,
.textarea {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 12rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  background-color: #fafafa;
  transition: all 0.3s;
}

.input:focus,
.textarea:focus {
  border-color: #4CAF50;
  background-color: #fff;
  box-shadow: 0 0 0 2rpx rgba(76, 175, 80, 0.2);
}

.input {
  height: 80rpx;
}

.textarea {
  min-height: 180rpx;
  padding: 20rpx;
}

.picker {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 12rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fafafa;
}

.picker-text {
  color: #333;
  font-size: 28rpx;
}

.icon-arrow {
  color: #999;
  font-size: 24rpx;
  transform: rotate(90deg);
}

.location-method {
  display: flex;
  gap: 20rpx;
}

.method-btn {
  flex: 1;
  padding: 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 12rpx;
  background-color: #fafafa;
  font-size: 26rpx;
  color: #666;
  transition: all 0.3s;
}

.method-btn.active {
  background: linear-gradient(90deg, #4CAF50, #2E7D32);
  color: #fff;
  border-color: #4CAF50;
}

.location-btn {
  width: 100%;
  padding: 25rpx;
  background: linear-gradient(90deg, #2196F3, #0D47A1);
  color: #fff;
  border: none;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.btn-text {
  font-size: 28rpx;
}

.location-display {
  padding: 20rpx;
  background-color: #f5f9ff;
  border-radius: 12rpx;
  border: 1rpx solid #e3f2fd;
}

.location-text {
  display: block;
  font-size: 26rpx;
  color: #333;
  line-height: 1.6;
}

.form-actions {
  display: flex;
  padding: 20rpx 0 40rpx;
  gap: 20rpx;
}

.cancel-btn,
.submit-btn {
  flex: 1;
  padding: 25rpx;
  border: none;
  border-radius: 12rpx;
  color: #fff;
  font-size: 28rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cancel-btn {
  background: linear-gradient(90deg, #9E9E9E, #616161);
}

.submit-btn {
  background: linear-gradient(90deg, #4CAF50, #2E7D32);
}

.image-upload-container {
  width: 100%;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 150rpx;
  height: 150rpx;
  border-radius: 12rpx;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.delete-image-btn {
  position: absolute;
  top: -12rpx;
  right: -12rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #ff5252;
  color: white;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  border: none;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.image-upload-btn {
  width: 150rpx;
  height: 150rpx;
  border: 2rpx dashed #4CAF50;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #4CAF50;
  text-align: center;
  background-color: #f5fff5;
}

.icon-add {
  font-size: 60rpx;
  font-weight: bold;
  margin-bottom: 5rpx;
}

.upload-text {
  font-size: 22rpx;
}

.icon-delete {
  font-size: 24rpx;
}
</style>